package name.jautzy.esi.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import name.jautzy.esi.client.model.EsiShip;
import name.jautzy.esi.client.model.EsiComment;
import name.jautzy.esi.client.model.EveFormula;
import name.jautzy.esi.client.model.Fit;
import name.jautzy.esi.client.model.Launcher;
import name.jautzy.esi.client.model.TargetShip;
import name.jautzy.esi.client.model.Turret;
import name.jautzy.esi.client.ressources.StandardRessources;

import com.extjs.gxt.charts.client.Chart;
import com.extjs.gxt.charts.client.model.ChartModel;
import com.extjs.gxt.charts.client.model.axis.RadarAxis;
import com.extjs.gxt.charts.client.model.axis.XAxis;
import com.extjs.gxt.charts.client.model.axis.YAxis;
import com.extjs.gxt.charts.client.model.charts.AreaChart;
import com.extjs.gxt.charts.client.model.charts.dots.BaseDot;
import com.extjs.gxt.charts.client.model.charts.dots.Dot;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.core.XTemplate;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.ProgressBar;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.Text;
import com.extjs.gxt.ui.client.widget.WidgetComponent;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.RowExpander;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.CenterLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Image;


public class DisplayEftFittingListener extends SelectionListener<ButtonEvent> {
	private CheckBoxSelectionModel<EsiShip> sm;
	private EsiShip esiShip;
	private Fit fit;
	public static NumberFormat format0D = NumberFormat.getFormat("# ##0");
	public static NumberFormat format1D = NumberFormat.getFormat("#0.#");
	public static NumberFormat format5D = NumberFormat.getFormat("#0.#####");
	public static NumberFormat format3D = NumberFormat.getFormat("#0.###");
	public static NumberFormat format2D = NumberFormat.getFormat("#0.##");
	public static String chartUrl = "ressources/chart/open-flash-chart.swf";
	
	
	public DisplayEftFittingListener (CheckBoxSelectionModel<EsiShip> sm) {
		super();
		this.sm = sm;
	}
	
	@Override
	public void componentSelected(ButtonEvent ce) {  

		esiShip = sm.getSelectedItem();
		if (esiShip==null) {
			MessageBox.info("Action", "Please Select something", null);
			return;
		}
        
        
        AsyncCallback<Fit> callback = new AsyncCallback<Fit>() {
			public void onSuccess(Fit result) {
				fit = result;
				final Window window = new Window();
		        window.setSize(760,520);
		        window.setResizable(false);
		        window.setHeading(esiShip.getGroupName()+" - "+esiShip.getShipTypeName()+" - "+esiShip.getShipName());
		        
		        String race = esiShip.getRace();
		        if (race.equals("Caldari"))
		        	window.setIcon(StandardRessources.getIcon(StandardRessources.LTLICONS.caldari()));
		        else if (race.equals("Amarr"))
		        	window.setIcon(StandardRessources.getIcon(StandardRessources.LTLICONS.amarr()));
		        else if (race.equals("Minmatar"))
		        	window.setIcon(StandardRessources.getIcon(StandardRessources.LTLICONS.minmatar()));
		        else if (race.equals("Gallente"))
		        	window.setIcon(StandardRessources.getIcon(StandardRessources.LTLICONS.gallente()));
		        
		        window.setLayout(new FitLayout());
		                
		        TabPanel tabPanel = new TabPanel();
		        addDefaultTab(tabPanel); 
		        addChartRangeTab(tabPanel); 
		        addChartEVTab(tabPanel); 
		        addChartTurretTab(tabPanel); 
		        addEFTTab(tabPanel);
		        addCommentTab(tabPanel);
		               
		        window.add(tabPanel);
				
				window.show();
			}

			public void onFailure(Throwable caught) {
				MessageBox.info("Action", "Can't load ship : "+caught.toString(), null); 
			}
		};
		Esi.getEsi().getFitService().getFit(esiShip.getId(), callback);
	}
	
	private void addCommentTab(TabPanel tabPanel) {
		TabItem panel = new TabItem("Comments");
		panel.setLayout(new FitLayout());
		
		ContentPanel cp = new ContentPanel();
		cp.setHeaderVisible(false);
		cp.setLayout(new FitLayout());
		
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  
		  
	    XTemplate tpl = XTemplate.create("<p><b>Corporation:</b> {corpo}</p><br><p><b>Alliance:</b> {ally}</p><br><p><b>Comment:</b></p><p> {comment}</p>");  
	  
	    RowExpander expander = new RowExpander();  
	    expander.setTemplate(tpl); 
	    
	    configs.add(expander);
	    
	    ColumnConfig column = new ColumnConfig();  
	    column.setId("nick");  
	    column.setHeader("Name");  
	    column.setWidth(200);  
	    configs.add(column);  
	    
	    column = new ColumnConfig("date", "Posted", 100);  
	    column.setAlignment(HorizontalAlignment.RIGHT);  
	    column.setDateTimeFormat(DateTimeFormat.getShortDateTimeFormat());  
	    configs.add(column); 
		
	    ColumnModel cm = new ColumnModel(configs);  
	    
	    RpcProxy<ListLoadResult<EsiComment>> sProxy = new RpcProxy<ListLoadResult<EsiComment>> () {
	    	@Override
	    	public void load(Object loadConfig, AsyncCallback<ListLoadResult<EsiComment>> callback) {
	    		Esi.getEsi().getLoginService().getComments(fit.getId(), callback);
	    	}
	    };
	    final ListLoader<ListLoadResult<EsiComment>> sLoader = new BaseListLoader<ListLoadResult<EsiComment>>(  
	            sProxy);  
	    //sLoader.setRemoteSort(true);
	    
	    ListStore<EsiComment> store = new ListStore<EsiComment>(sLoader); 
	    sLoader.load();
	   
	    /*EsiComment test = new EsiComment();
	    test.setAlly("toto");
	    test.setCorpo("titi");
	    test.setNick("Moi");
	    test.setComment("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.<br/><br/>Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt diam nec urna. Curabitur velit."); 
	    test.setDate(new Date());
	    store.add(test);*/
	    
	    Grid<EsiComment> grid = new Grid<EsiComment>(store, cm);  
	    grid.addPlugin(expander);  
	    grid.getView().setAutoFill(true);  
	    
	    cp.add(grid); 
	    
	    Button button = new Button("Add Comment");
	    button.addSelectionListener(new AddCommentListener(store, fit.getId()));
	    ToolBar toolBar = new ToolBar();  
	    toolBar.add(button);
	    cp.setTopComponent(toolBar);
		
	    panel.add(cp);
		tabPanel.add(panel);
	}
	
	private void addEFTTab(TabPanel tabPanel) {
		TabItem panel = new TabItem("EFT");
		panel.setLayout(new FitLayout());
		TextArea ta = new TextArea();
		ta.setReadOnly(true);
		ta.setValue(fit.getEftFit());
		panel.add(ta);
		tabPanel.add(panel);
	}
	
	private void addChartRangeTab(TabPanel tabPanel) {
		TabItem panel = new TabItem("Dps vs Range");
		panel.setLayout(new FitLayout());
		final Chart chart = new Chart(chartUrl);  
	    chart.setBorders(true);  
	    
	    ChartModel cm = new ChartModel();  
	    cm.setBackgroundColour("#fffff5");  
	    
	    EveFormula formula = new EveFormula(fit);
	    double optimal = formula.bestOptimal();
	    double min = 0;
	    double max = 0;
	    int steps = 20;
	   	    
	    if (optimal < 30000)
	    	max = 50000;
	    
	    else if (optimal <100000 ) 
	    	max = 120000;
	    else if (optimal <200000 )
	    	max = 220000;
	    else
	    	max = 250000;
	    
	    double maxDps = formula.maxDps();
	    
	    XAxis xa = new XAxis(); 
	    xa.setMax(max/1000.0);
	    xa.setSteps(max/10000.0);
	    cm.setXAxis(xa);
	    
	    YAxis ya = new YAxis();
	    if (maxDps < 900)
	    	ya.setMax(1000);
	    else 
	    	ya.setMax(2000);
	    
	    cm.setYAxis(ya);
	      
	    AreaChart area1 = new AreaChart();  
	    area1.setFillAlpha(0.3f);  
	    area1.setColour("#ff0000");  
	    area1.setFillColour("#ff0000");  
	    
	    for (Double d : EveFormula.genXAxys(min, max, steps) ) {
	    	BaseDot dot = new Dot();
	    	dot.setXY(d/1000.0, formula.totalDps(d));
	    	area1.addDots(dot);
	    }
   
	    cm.addChartConfig(area1);  
	    chart.setChartModel(cm);
	    panel.add(chart);
	    tabPanel.add(panel);
		
	}
	
	private void addChartTurretTab(TabPanel tabPanel) {
		TabItem panel = new TabItem("Tank vs Ships");
		panel.setLayout(new FitLayout());
		final Chart chart = new Chart(chartUrl);  
	    chart.setBorders(true);  
	    
	    ChartModel cm = new ChartModel();  
	    cm.setBackgroundColour("#fffff5");  
	    
	    EveFormula formula = new EveFormula(fit);
	    
	    RadarAxis ra = new RadarAxis();  
	    ra.setMax(EveFormula.maxTime); 
	    ra.setSteps(100);
	    ra.setStroke(2);  
	    ra.setColour("#A1D4B5");  
	    ra.setGridColour("#C0DEBF");  
	    ra.setSpokeLabels("BS Snipe T","BS Snipe M","HAC Long T", "HAC Long M", "AF T", "AF M", "HAC Close", "HAC Close M", "BS Close T", "BS Close M");  
	    cm.setRadarAxis(ra);  
	    
	    AreaChart area = new AreaChart();  
	    area.setFillAlpha(0.3f);  
	    area.setColour("#ff9900");  
	    area.setFillColour("#ff6600");  
	    area.setLoop(true);  
	    
	    area.addValues(formula.timeToDeath(1,Turret.LL));
	    area.addValues(formula.timeToDeath(1,Launcher.Cruise));
	    area.addValues(formula.timeToDeath(1,Turret.ML));
	    area.addValues(formula.timeToDeath(1,Launcher.Heavy));
	    area.addValues(formula.timeToDeath(1,Turret.SC));
	    area.addValues(formula.timeToDeath(1,Launcher.Light));
	    area.addValues(formula.timeToDeath(1,Turret.MC));
	    area.addValues(formula.timeToDeath(1,Launcher.HAM));
	    area.addValues(formula.timeToDeath(1,Turret.LC));
	    area.addValues(formula.timeToDeath(1,Launcher.Siege));
	    
	    cm.addChartConfig(area);  
	    chart.setChartModel(cm);
	    panel.add(chart);
	    tabPanel.add(panel);
		
	}
	
	private void addChartEVTab(TabPanel tabPanel) {
		TabItem panel = new TabItem("Dps vs Ships");
		panel.setLayout(new FitLayout());
		final Chart chart = new Chart(chartUrl);  
	    chart.setBorders(true);  
	    
	    ChartModel cm = new ChartModel();  
	    cm.setBackgroundColour("#fffff5");  
	    
	    EveFormula formula = new EveFormula(fit);
	    double maxDps = formula.maxDps();
	    
	    XAxis xa = new XAxis();
	    xa.setLabels("Inty", "Logi", "HAS", "BC", "BS");
	    cm.setXAxis(xa);
	    
	    YAxis ya = new YAxis();
	    if (maxDps < 900)
	    	ya.setMax(1000);
	    else 
	    	ya.setMax(2000);
	    
	    cm.setYAxis(ya);
	    
	    AreaChart area = new AreaChart();  
	    area.setFillAlpha(0.3f);  
	    area.setColour("#ff9900");  
	    area.setFillColour("#ff6600");  
	    
	    area.addValues(formula.totalDps(TargetShip.inty));
	    area.addValues(formula.totalDps(TargetShip.logi));
	    area.addValues(formula.totalDps(TargetShip.HAS));
	    area.addValues(formula.totalDps(TargetShip.BC));
	    area.addValues(formula.totalDps(TargetShip.BS));
	    
	    cm.addChartConfig(area);  
	    chart.setChartModel(cm);
	    panel.add(chart);
	    tabPanel.add(panel);
		
	}
	
	private void addDefaultTab(TabPanel tabPanel) {
		TabItem tab = new TabItem("default");
		tab.setLayout(new BorderLayout());
		
		ContentPanel north = new ContentPanel();
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 160);  
	    //northData.setMargins(new Margins(5));  
	    northData.setSplit(false); 
	    northData.setCollapsible(false);

		ContentPanel east = new ContentPanel();
		BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST,210);  
		//eastData.setMargins(new Margins(5));  
		eastData.setSplit(false); 
		eastData.setCollapsible(false);
		
		ContentPanel west = new ContentPanel();
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST,210);  
		//eastData.setMargins(new Margins(5));  
		westData.setSplit(false); 
		westData.setCollapsible(false);
	    
		ContentPanel south = new ContentPanel();
		BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 100);  
		//southData.setMargins(new Margins(5));  
		southData.setSplit(false); 
		southData.setCollapsible(false);
	    
		ContentPanel center = new ContentPanel();
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
		//centerData.setMargins(new Margins(5));  
		centerData.setSplit(false); 
		centerData.setCollapsible(false);
		
		generateCenterZone(center);
		generateWestZone(west);
		generateSouthZone(south);
		generateEastZone(east);
		generateNorthZone(north);
		
		tab.add(north,northData);
		tab.add(east,eastData);
		tab.add(west,westData);
		tab.add(south,southData);
		tab.add(center,centerData);
		
		tabPanel.add(tab);
	}
	
	void generateCenterZone(ContentPanel center) {
		center.setLayout(new CenterLayout());
		ContentPanel panel = new ContentPanel();
		center.setHeaderVisible(true);
		center.setHeading("Slot Layout");
		TableLayout layout = new TableLayout(8);
		layout.setCellSpacing(0);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		layout.setBorder(1);
		
		panel.setLayout(layout);
		panel.setHeaderVisible(false);
		createRowSlots(panel,fit.getHighSlotsIcon(),fit.getHighSlots(),fit.getMaxHighSlots(),StandardRessources.STDICONS.emptyHighSlot(),8);
		createRowSlots(panel,fit.getMedSlotsIcon(),fit.getMedSlots(),fit.getMaxMedSlots(),StandardRessources.STDICONS.emptyMedSlot(),8);
		createRowSlots(panel,fit.getLowSlotsIcon(),fit.getLowSlots(),fit.getMaxLowSlots(),StandardRessources.STDICONS.emptyLowSlot(),8);
		createRowSlots(panel,fit.getRigSlotsIcon(),fit.getRigSlots(),fit.getMaxRigSlots(),StandardRessources.STDICONS.emptyRigSlot(),3);
		int maxSubSlot = 0;
		if (esiShip.getTechLevel()==3)
			maxSubSlot = 5;
		createRowSlots(panel,fit.getSubsystemsIcon(),fit.getSubsystems(),maxSubSlot,StandardRessources.STDICONS.emptySubsystemSlot(),5);
		
		panel.setBodyBorder(false);
		
		center.add(panel);
	}
	
	void createRowSlots(ContentPanel center, List<Integer> listIcon, List<String> listModules, long maxSlots, ImageResource emptyIcon, int max ) {
		
		TableData data32 = new TableData("32","32");
		Iterator<Integer> itIcon = listIcon.iterator();
		Iterator<String> itMod = listModules.iterator();
		for (int i =0; i<max; i++) {
			Image img =null;
			Integer icon = null;
			String module = "Empty Slot";
			if (i<listIcon.size()) {
				icon = itIcon.next();
				module = itMod.next();;
			}
			
			if (icon==null)
				img = AbstractImagePrototype.create(emptyIcon).createImage();
			else {
				img = StandardRessources.getImage(icon);
			}
			
			WidgetComponent wc = new WidgetComponent(img);
			wc.setToolTip(module);
			
			if (i<maxSlots)
				center.add(wc,data32);
			else
				center.add(new Text(""),data32);
			
		}
	}
	
	void generateWestZone(ContentPanel west) {
		
		TableLayout layout = new TableLayout(4);
		layout.setCellSpacing(5);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		west.setLayout(new CenterLayout());
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(layout);
		
		TableData data32 = new TableData("50","32");
		TableData data16 = new TableData("50","16");
		panel.add(new Text(""),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.shield()).createImage(),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.armor()).createImage(),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.structure()).createImage(),data32);
		panel.add(new Text("Hp"),data16);
		panel.add(new Text(new Long((long)fit.getShieldHP()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getArmorHP()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getStructHP()).toString()),data16);
		panel.add(new Text("Hrs"),data16);
		double temp = 2.5*fit.getShieldHP()/fit.getShieldRechTime();
		if (fit.getShieldBoostDuration()!=0)
			temp+=fit.getShieldBoost()/fit.getShieldBoostDuration();
		panel.add(new Text(new Long((long)temp).toString()),data16);
		temp = 0;
		if (fit.getArmorRepairDuration()!=0)
			temp = fit.getArmorRepair()/fit.getArmorRepairDuration();
		panel.add(new Text(new Long((long)temp).toString()),data16);
		panel.add(new Text(""),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.LTLICONS.em()).createImage());
		temp = (1.0-fit.getEmSR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getEmAR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getStructResonance())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.LTLICONS.thermal()).createImage());
		temp = (1.0-fit.getThSR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getThAR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getStructResonance())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.LTLICONS.kinetic()).createImage());
		temp = (1.0-fit.getKiSR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getKiAR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getStructResonance())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.LTLICONS.explosive()).createImage());
		temp = (1.0-fit.getExSR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getExAR())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		temp = (1.0-fit.getStructResonance())*100.0;
		panel.add(new Text(new Long((long)temp).toString()+"%"),data16);
		
		panel.setBodyBorder(false);
		
		StringBuffer buffer = new StringBuffer("Effective Hp : ");
		buffer.append(new Long((long)esiShip.getEffHp()));
		west.setHeading(buffer.toString());
		west.add(panel);
	}
	
	void generateSouthZone(ContentPanel south) {
		TableLayout layout = new TableLayout(6);
		layout.setCellSpacing(10);
		layout.setCellHorizontalAlign(HorizontalAlignment.LEFT);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		south.setLayout(new CenterLayout());
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(layout);
		
		CheckBox cloak = new CheckBox();
		cloak.setBoxLabel("Cloak");
		cloak.setValue(fit.getCloak());
		cloak.setEnabled(false);
		panel.add(cloak);
		
		CheckBox scramble = new CheckBox();
		scramble.setBoxLabel("Scramble");
		scramble.setValue(fit.getScramble());
		scramble.setEnabled(false);
		panel.add(scramble);
		
		
		CheckBox paint = new CheckBox();
		paint.setBoxLabel("Painter");
		paint.setValue(fit.getPaint());
		paint.setEnabled(false);
		panel.add(paint);
		
		CheckBox vamp = new CheckBox();
		vamp.setBoxLabel("Vampire");
		vamp.setValue(fit.getNos());
		vamp.setEnabled(false);
		panel.add(vamp);
		
		CheckBox td = new CheckBox();
		td.setBoxLabel("Tracking Disruption");
		td.setValue(fit.getTrackingDisrupt());
		td.setEnabled(false);
		panel.add(td);
		
		CheckBox rs = new CheckBox();
		rs.setBoxLabel("Remote Shield");
		rs.setValue(fit.getRemoteShield());
		rs.setEnabled(false);
		panel.add(rs);
		
		CheckBox ecm = new CheckBox();
		ecm.setBoxLabel("ECM");
		ecm.setValue(fit.getEcm());
		ecm.setEnabled(false);
		panel.add(ecm);
		
		CheckBox web = new CheckBox();
		web.setBoxLabel("Webifier");
		web.setValue(fit.getWeb());
		web.setEnabled(false);
		panel.add(web);
		
		CheckBox damp = new CheckBox();
		damp.setBoxLabel("Dampener");
		damp.setValue(fit.getDamp());
		damp.setEnabled(false);
		panel.add(damp);
		
		CheckBox neutra = new CheckBox();
		neutra.setBoxLabel("Neutralizer");
		neutra.setValue(fit.getNeutra());
		neutra.setEnabled(false);
		panel.add(neutra);
		
		CheckBox warpImmune = new CheckBox();
		warpImmune.setBoxLabel("Bubble Immunity");
		warpImmune.setValue(fit.getWarpImmune());
		warpImmune.setEnabled(false);
		panel.add(warpImmune);
		
		CheckBox ra = new CheckBox();
		ra.setBoxLabel("Remote Armor");
		ra.setValue(fit.getRemoteArmor());
		ra.setEnabled(false);
		panel.add(ra);
		
		StringBuffer buffer = new StringBuffer("Projected Effects");
		if (esiShip.getPvp())
			buffer.append(" - PVP");
		if (esiShip.getPve())
			buffer.append(" - PVE");
		south.setHeading(buffer.toString());
		panel.setBodyBorder(false);
		south.add(panel);
	}
	
void generateEastZone(ContentPanel east) {
		
		TableLayout layout = new TableLayout(4);
		layout.setCellSpacing(5);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		east.setLayout(new CenterLayout());
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(layout);
		
		TableData data32 = new TableData("50","32");
		TableData data16 = new TableData("50","16");
		panel.add(new Text(""),data32);
		WidgetComponent launcher = new WidgetComponent(StandardRessources.getIcon(StandardRessources.STDICONS.launcher()).createImage());
		if (fit.getLauncherAmmoName()!=null)
			launcher.setToolTip(fit.getLauncherAmmoName());
		WidgetComponent turret = new WidgetComponent(StandardRessources.getIcon(StandardRessources.STDICONS.turret()).createImage());
		if (fit.getTurretAmmoName()!=null)
			turret.setToolTip(fit.getTurretAmmoName());
		WidgetComponent drone = new WidgetComponent(StandardRessources.getIcon(StandardRessources.STDICONS.drones()).createImage());
		panel.add(launcher,data32);
		panel.add(turret,data32);
		panel.add(drone,data32);
		panel.add(new Text("Alpha"),data16);
		panel.add(new Text(new Long((long)fit.getMissileAlpha()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getTurretAlpha()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getDroneAlpha()).toString()),data16);
		panel.add(new Text("Dps"),data16);
		panel.add(new Text(new Long((long)fit.getMaxMissileDps()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getMaxTurretDps()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getMaxDroneDps()).toString()),data16);
		panel.add(new Text("Optimal"),data16);
		panel.add(new Text(format1D.format(fit.getMissileVelocity()*fit.getMissileFlightTime()/1000.0)),data16);
		panel.add(new Text(format1D.format(fit.getTurretOptimal()/1000.0)),data16);
		panel.add(new Text(format1D.format(fit.getDroneRange()/1000.0)),data16);
		panel.add(new Text("Falloff"),data16);
		panel.add(new Text(""),data16);
		panel.add(new Text(format1D.format(fit.getTurretFalloff()/1000.0)),data16);
		panel.add(new Text(""),data16);
		panel.add(new Text("Signature"),data16);
		panel.add(new Text(new Long((long)fit.getMissileExploRadius()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getTurretSignature()).toString()),data16);
		panel.add(new Text(new Long((long)fit.getDroneSignature()).toString()),data16);
		Text tevText = new Text("TT/EV");
		tevText.setToolTip("Turret Tracking / Explosion Velocity");
		panel.add(tevText,data16);
		panel.add(new Text(new Long((long)fit.getMissileExploVelocity()).toString()),data16);
		panel.add(new Text(format5D.format(fit.getTurretTracking())),data16);
		panel.add(new Text(format5D.format(fit.getDroneTracking())),data16);
		
		panel.setBodyBorder(false);
		
		StringBuffer buffer = new StringBuffer("Max Dps : ");
		buffer.append(new Long((long)(fit.getMaxMissileDps()+fit.getMaxTurretDps()+fit.getMaxDroneDps())));
		east.setHeading(buffer.toString());
		east.add(panel);
	}

	void generateNorthZone(ContentPanel north) {
		north.setLayout(new BorderLayout());
		north.setHeaderVisible(false);

		ContentPanel astroPanel = new ContentPanel();
		ContentPanel targetPanel = new ContentPanel();
		ContentPanel iconPanel = new ContentPanel();
				
		generateAstroPanel(astroPanel);
		generateTargetPanel(targetPanel);
		generateIconPanel(iconPanel);
		
		BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 100);  
	    //northData.setMargins(new Margins(5));  
	    southData.setSplit(false); 
	    southData.setCollapsible(false);
	    
	    BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST, 210);  
	    //northData.setMargins(new Margins(5));  
	    eastData.setSplit(false); 
	    eastData.setCollapsible(false);
	    
	    BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
	    //northData.setMargins(new Margins(5));  
	    centerData.setSplit(false); 
	    centerData.setCollapsible(false);
	    
	    BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 210);  
	    //northData.setMargins(new Margins(5));  
	    westData.setSplit(false); 
	    westData.setCollapsible(false);
	    
	    BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 100);  
	    //northData.setMargins(new Margins(5));  
	    northData.setSplit(false); 
	    northData.setCollapsible(false);
	    
	    
	    
	    
		
		north.add(astroPanel, westData);
		north.add(targetPanel, eastData);
		north.add(iconPanel, centerData);
	}

	void generateIconPanel(ContentPanel icon) {
		icon.setLayout(new CenterLayout());
		icon.setHeaderVisible(true);
		icon.setHeading("Ressources");
		
		TableLayout layout = new TableLayout(2);
		layout.setCellSpacing(1);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		ContentPanel panel = new ContentPanel();
		panel.setLayout(layout);
		panel.setHeaderVisible(false);
		
		TableData data128 = new TableData("128","128");
		data128.setRowspan(4);
		
		TableData data32 = new TableData("128","32");
		
		StringBuffer imgPath = new StringBuffer("ressources/images/128_128/");
		imgPath.append(fit.getShipId());
		imgPath.append(".png");
		
		Image img = new Image(imgPath.toString());
		panel.add(img,data128);
		
		ProgressBar cpuBar = new ProgressBar();
		double ratio = 1.0;
		double div = fit.getMaxCpu();
		double num = fit.getCpu();
		if (div!=0)
			ratio = num/div;
		cpuBar.setWidth(100);
		StringBuffer buffer = new StringBuffer(format1D.format(num));
		buffer.append(" / ").append(format1D.format(div));
		cpuBar.setToolTip(buffer.toString());
		cpuBar.setIncrement(100);
		cpuBar.updateProgress(ratio, "CPU");
		
		ProgressBar powerBar = new ProgressBar();
		ratio = 1.0;
		div = fit.getMaxPower();
		num = fit.getPower();
		if (div!=0)
			ratio = num/div;
		powerBar.setWidth(100);
		buffer = new StringBuffer(format1D.format(num));
		buffer.append(" / ").append(format1D.format(div));
		powerBar.setToolTip(buffer.toString());
		powerBar.setIncrement(100);
		powerBar.updateProgress(ratio, "Power");
		
		ProgressBar calibBar = new ProgressBar();
		ratio = 1.0;
		div = fit.getMaxCalibration();
		num = fit.getCalibration();
		if (div!=0)
			ratio = num/div;
		calibBar.updateProgress(ratio, "Calibration");
		calibBar.setWidth(100);
		buffer = new StringBuffer(format1D.format(num));
		buffer.append(" / ").append(format1D.format(div));
		calibBar.setToolTip(buffer.toString());
		
		ProgressBar capaBar = new ProgressBar();
		ratio = 1.0;
		double capa = fit.getCapacitor();
		double rechTime = fit.getCapRechargeTime();
		double capUsage = fit.getCapUsage()+fit.getBoostCapUsage();
		double tdur = fit.getTurretRof();
		if (tdur != 0)
			capUsage+=fit.getTurretCapa()/tdur;
		div = 2.5*capa/rechTime;
		if (div!=0)
			ratio = capUsage/div;
		if (ratio <= 1)
			capaBar.updateProgress(ratio, "Cap Stable");
		else 
			capaBar.updateProgress(ratio, "Not Cap Stable");
		capaBar.setWidth(100);
		buffer = new StringBuffer("Capacitor : ");
		buffer.append(format1D.format(capa));
		buffer.append(" - Recharge Time : ").append(format1D.format(rechTime));
		buffer.append(" - Cap usage : ").append(format1D.format(capUsage));
		buffer.append(" / ").append(format1D.format(div));
		capaBar.setToolTip(buffer.toString());
	
		
		panel.add(cpuBar,data32);
		panel.add(powerBar,data32);
		panel.add(calibBar,data32);
		//panel.add(capaBar,data32);
		
		panel.setBodyBorder(false);
		
		icon.add(panel);
	}
	
	void generateTargetPanel(ContentPanel target) {
		target.setLayout(new CenterLayout());
		
		TableLayout layout = new TableLayout(4);
		layout.setCellSpacing(1);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(layout);
		
		TableData data32 = new TableData("50","32");
		//data32.setRowspan(2);
		
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.targetRange()).createImage(),data32);
		panel.add(new Text(format1D.format(fit.getTargetRange()/1000.0)),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.maxTarget()).createImage(),data32);
		panel.add(new Text(format1D.format(fit.getMaxTarget())),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.scanReso()).createImage(),data32);
		panel.add(new Text(format1D.format(fit.getScanResolution())),data32);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.sensorStrength()).createImage(),data32);
		panel.add(new Text(format1D.format(fit.getSensorStrength())),data32);
		
		target.setHeading("Targeting");
		panel.setBodyBorder(false);
		
		target.add(panel);
	}
	
	void generateAstroPanel(ContentPanel astro) {
		astro.setLayout(new CenterLayout());
		
		TableLayout layout = new TableLayout(4);
		layout.setCellSpacing(1);
		layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
		layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(layout);
		
		TableData data32 = new TableData("50","32");
		data32.setRowspan(2);
		TableData data16 = new TableData("50","16");
		
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.speed()).createImage(),data32);
		panel.add(new Text(new Long((long)fit.getVelocity()).toString()),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.agility()).createImage(),data32);
		panel.add(new Text(format3D.format(fit.getAgility())),data32);
		panel.add(new Text(new Long((long)fit.getBoostedVelocity()).toString()),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.signature()).createImage(),data32);
		panel.add(new Text(new Long((long)fit.getSignature()).toString()),data16);
		panel.add(StandardRessources.getIcon(StandardRessources.STDICONS.alignTime()).createImage(),data32);
		double alignTime = -1.024*Math.log(0.25)*fit.getMass()*fit.getAgility()/1000000.0;
		double alignTimeBoosted = -1.024*Math.log(0.25)*(fit.getMass()+fit.getBoostedMass())*fit.getAgility()/1000000.0;
		panel.add(new Text(format1D.format(alignTime)),data16);
		double bsig = fit.getBoostRadiusFactor();
		double boostedSig = fit.getSignature();
		if (bsig!=0)
			boostedSig*=bsig;
		panel.add(new Text(new Long((long)(boostedSig)).toString()),data16);
		panel.add(new Text(format1D.format(alignTimeBoosted)),data16);
		panel.add(new Text("sigvel"),data32);panel.add(new Text(format2D.format(fit.getSignature()/fit.getVelocity())),data16);
		panel.add(new Text(""),data32);panel.add(new Text(""),data16);
		panel.add(new Text(format2D.format(boostedSig/fit.getBoostedVelocity())),data16);
		
		panel.setBodyBorder(false);
		astro.setHeading("Mobility");
		
		astro.add(panel);
	}
}
